package fina2.dcs.returns;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.faces.context.FacesContext;
import javax.naming.InitialContext;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.jboss.annotation.ejb.LocalBinding;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.log.Log;

import fina2.dcs.common.UIComponentHelper;
import fina2.dcs.context.ContextHelper;
import fina2.dcs.i18n.LanguageSession;
import fina2.dcs.system.SysString;
import fina2.dcs.system.SysStringLocal;
import fina2.dcs.system.SysStringPk;

@Stateful
@Name("returnTypeSession")
@Scope(ScopeType.SESSION)
@LocalBinding(jndiBinding = "ReturnTypeSession/local")
@SuppressWarnings("unchecked")
@AutoCreate
public class ReturnTypeSession implements ReturnTypeLocal,Serializable {
	@PersistenceContext
	private EntityManager em;
	
	@Logger
	private Log log;

	private InitialContext ic = null;

	private SysStringLocal sysStringLocal = null;

	@DataModel
	private List<ReturnType> returnTypes = new ArrayList<ReturnType>();

	private ReturnType returnType = new ReturnType();

	private ReturnType selectedRetType = new ReturnType();

	private String code = null;

	private String description = null;

	private boolean success = false;

	private final BigDecimal defaultIndex = new BigDecimal("1");

	public void init() {
		log.info("Initializing Return Types...");
		try {
			ic = ContextHelper.getInitialContext();
			sysStringLocal = ContextHelper.injectSysStringLocal(ic);

			returnTypes = em.createQuery("FROM " + ReturnType.class.getName() + " r ORDER BY r.code ASC").getResultList();

			List<BigDecimal> retTypesStrIds = new ArrayList<BigDecimal>();

			for (int i = 0; i < returnTypes.size(); i++) {
				retTypesStrIds.add(returnTypes.get(i).getNameStrId());
			}

			StringBuffer sb = new StringBuffer(retTypesStrIds.toString());
			sb.replace(0, 1, "");
			sb.replace(sb.toString().length() - 1, sb.toString().length(), "");

			List<SysString> descriptions = sysStringLocal.getAllValues(sb.toString(), LanguageSession.langId);

			for (int i = 0; i < returnTypes.size(); i++)
				for (int j = 0; j < descriptions.size(); j++) {
					if (returnTypes.get(i).getNameStrId().toString().trim().equals(descriptions.get(j).getPk().getId().toString())) {
						returnTypes.get(i).setDescription(descriptions.get(j).getValue());
						break;
					}
				}

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
	}

	public String addReturnType() {
		log.info("Adding Return Type " + returnType.getCode());
		try {
			ReturnType rt = new ReturnType();
			rt.setCode(returnType.getCode());
			rt.setId(getMaxId().add(defaultIndex));
			rt.setNameStrId(sysStringLocal.getMaxId().add(defaultIndex));
			em.persist(rt);

			SysStringPk pk = new SysStringPk();
			pk.setId(rt.getNameStrId());
			pk.setLangId(LanguageSession.langId);
			SysString ss = new SysString();
			ss.setValue(returnType.getDescription());
			ss.setPk(pk);
			sysStringLocal.addString(ss);
			success = true;
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		} finally {
			returnType = new ReturnType();
		}
		return "returnTypeAdded";
	}

	public String updateReturnType() {
		log.info("Updating Return Type");
		try {
			ReturnType rt = em.find(ReturnType.class, selectedRetType.getId());
			rt.setCode(selectedRetType.getCode());
			em.merge(rt);

			SysStringPk pk = new SysStringPk(selectedRetType.getNameStrId(),LanguageSession.langId);
			SysString ss = sysStringLocal.findByPk(pk);
			ss.setValue(description);
			sysStringLocal.updateString(ss);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		} finally {
			selectedRetType = new ReturnType();
			description = null;
		}
		return "returnTypeUpdated";
	}

	public void removeReturnType() {
		log.info("Removing Return Type " + code);
		try {
			ReturnType rt = findByCode(code);
			BigDecimal id = rt.getNameStrId();
			em.remove(rt);

			SysStringPk pk = new SysStringPk(id, LanguageSession.langId);
			sysStringLocal.removeString(pk);
			success = true;
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
	}

	public ReturnType findByCode(String code) {
		ReturnType rt = null;
		try {
			rt = (ReturnType) em.createQuery("FROM " + ReturnType.class.getName() + " r WHERE RTRIM(r.code)=?").setParameter(1, code.toString()).getSingleResult();
		} catch (NoResultException ex) {
			rt = null;
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return rt;
	}

	public BigDecimal getMaxId() {
		BigDecimal maxId = new BigDecimal("0");
		try {
			maxId = (BigDecimal) em.createQuery("SELECT MAX(r.id) FROM " + ReturnType.class.getName() + " r").getSingleResult();
			if (maxId == null)
				maxId = defaultIndex;
		} catch (NoResultException ex) {
			maxId = defaultIndex;
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return maxId;
	}

	public List<ReturnType> getReturnTypes() {
		return returnTypes;
	}

	public void setReturnTypes(List<ReturnType> returnTypes) {
		this.returnTypes = returnTypes;
	}

	public ReturnType getReturnType() {
		return returnType;
	}

	public void setReturnType(ReturnType returnType) {
		this.returnType = returnType;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public ReturnType getSelectedRetType() {
		return selectedRetType;
	}

	public void setSelectedRetType(ReturnType selectedRetType) {
		UIComponentHelper.clearComponent(FacesContext.getCurrentInstance().getViewRoot());
		this.selectedRetType = selectedRetType;
		success = false;
		description = selectedRetType.getDescription();
	}

	@Remove
	@Destroy
	public void remove() {

	}
}
